﻿using System;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;

using Unity;

using pri.smilly.QuickStart.Config;

namespace pri.smilly.QuickStart {
    public static class ApplicationContext {
        private static IUnityContainer _container;

        public static void Initialize() {
            Initialize("unity", string.Empty);
        }

        public static void Initialize(string containerName) {
            Initialize("unity", containerName);
        }

        public static void Initialize(string sectionName, string containerName) {
            _container = new UnityContainer();
            var section = ConfigurationManager.GetSection(sectionName) as UnityConfigurationSection;
            if (null != section) _container.LoadConfiguration(section, containerName);
            new ContainerConfigurator(_container, AppDomain.CurrentDomain.GetAssemblies()).Config();
        }

        public static T GetBean<T>() where T : class {
            try {
                return _container.Resolve<T>();
            } catch {
                return GetBean<T>(typeof(T).Name);
            }
        }

        public static T GetBean<T>(string name) where T : class {
            return _container.Resolve<T>(name);
        }

    }
}
